const ChatCompletion = require('@baiducloud/qianfan')
const speechSynthesis = require('../speechSynthesis/index')
// 通过参数初始化，设置安全认证ACCESS_KEY/SECRET_KEY，以对话Chat为例，调用如下
const client = new ChatCompletion.ChatCompletion(
    {
        version: 'v2',
        QIANFAN_ACCESS_KEY: '695eb64e92a84e01b555da333fd04112',
        QIANFAN_SECRET_KEY: '6bf3f77ad3a84feba32d92e4bef776b9'

    });
let timerId = null
async function getAIData(data) {
    // let selectSql =''
    // let selectTotalSql =''
    // const selectRows = await global.sql(selectSql)
    // const selectTotal = await global.sql(selectTotalSql)
        console.log('data');
        console.log(data);
    try {
        const resp = await client.chat({
            messages: [
                {
                    role: "user",
                    content: `${data}，时间<>包住，景点用[]包住，我的要求不要输出`,
                },
            ],
            stream: true,
            top_p: 0.7
        }, "ERNIE-4.0-8K");
        console.log('resp');
        console.log(resp);
        return resp
    } catch (error) {
        console.log(error);
        return {
            code: 500,
            msg: '请求失败',
            data: null
        }
    }


    // return {
    //     code: 200,
    //     msg: '请求成功',
    //     data: {
    //         list: selectRows,
    //         total: selectTotal[0].total
    //     }
    // }
}

async function generateArticle(data) {
    console.log('data');
    const { text, userId } = data
    try {
        const resp = await client.chat({
            messages: [
                {
                    role: "user",
                    content: text,
                },
            ],
            top_p: 0.7,
        }, "ERNIE-4.0-8K");
        consolelog('=============================resp.result====================================')
        consolelog(resp.result)
        consolelog('=============================resp.result====================================')
        const arr = resp.result.split('\n');
        // 使用filter()方法去除空字符串
        const nArr = arr.filter(paragraph => paragraph !== "");
        const content = nArr.filter((item, index) => index !== 0)
        const title = nArr[0].split(': ')
        const str = content.toString()
        const mData = await speechSynthesis.speechSynthesis({
            text: str
        })
        const dateTime = global.commonFun.getNowTime()
        let addAudioSql = `INSERT INTO audio(taskId,createTime) VALUES(?,?)`
        const addAudioParams = [mData.TaskId, dateTime];
        const addAudioRow = await global.sql(addAudioSql, addAudioParams)
        global.audioFileIdList.push(mData.TaskId)
        let addSql = `INSERT INTO article(title,content,createTime,audioId,createBy) VALUES(?,?,?,?,?)`
        const addSqlParams = [title[1], JSON.stringify(content), dateTime, addAudioRow.data.insertId, userId];
        const addRow = await global.sql(addSql, addSqlParams)
        return {
            code: 200,
            msg: '请求成功',
            data: {
                title: title[1],
                content: content
            }
        }
    } catch (error) {
        console.log(error);
        return {
            code: 500,
            msg: '请求成功',
            data: null
        }
    }
}

async function settTmerId() {
    timerId = setInterval(() => {
        console.log('每隔 1 秒执行定时任务');
        if (global.audioFileIdList.length === 0) {
            clearTimeout(timerId); // 取消定时任务
        } else {
            global.audioFileIdList.forEach(item => {
                speechSynthesis.getWorkByTaskId({
                    taskId: item
                })
            })
        }
    }, 2000); // 每隔 1 秒执行回调函数
}

exports.getAIData = getAIData
exports.generateArticle = generateArticle
